<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 页面上方工具条 -->
      <PageTools :show-before="true">
        <span slot="before">共166条记录</span>
        <span slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=employee')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </span>
      </PageTools>

      <!-- 页面下方的内容 -->
      <el-card>
        <el-table :data="list" border>
          <el-table-column label="序号" sortable="">
            <template slot-scope="{ $index }">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" sortable="" :formatter="formatEmployment" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template slot-scope="{row}">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" align="middle" style="height: 60px;">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageSetting.total"
            :page-size="pageSetting.size"
            :page-sizes="[2,5,10,20,50]"
            @current-change="currentChange"
            @size-change="sizeChange"
          />
        </el-row>
      </el-card>

      <!-- 新增弹出框 -->
      <AddEmployee :show-dialog.sync="showDialog" @addEmployee="getUserList" />
    </div>
  </div>
</template>

<script>
import { getUserList, delEmployee } from '@/api/employees'
// 引入字典
import EmploymentEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import { formatDate } from '@/filters'
export default {
  components: {
    AddEmployee
  },
  data() {
    return {
      showDialog: false,
      list: [],
      pageSetting: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 因为库太大了，所以按需要动态引入库
    async exportData() {
      // 因为表头需要中文, 但是拿数据的时候又是英文 key 所以必须
      // 做一个枚举对应
      const headersEnum = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      const header = Object.keys(headersEnum)
      // ["姓名", "手机号", "入职日期", "聘用形式", "转正日期", "工号", "部门"]
      console.log(header)
      // 获取所有的数据, 其实是根据当前的total 决定获取多少条
      const pageSetting = {
        page: 1,
        size: this.pageSetting.total
      }
      // 用引入的原 api 接口发送请求
      const { rows } = await getUserList(pageSetting)
      console.log(rows)

      // 映射出由对象组成的行数据，变为一个个员工数组
      const data = rows.map(item => {
        // 这里是遍历拿到的所有数据, 每个员工都是对象
        // 需要转换为数组
        return this.obj2Array(item, headersEnum)
      })

      // 异步引入导出库
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header,
        data
      })
    },
    obj2Array(item, dictionary) {
      const array = []
      // console.log(item)
      // 当前我们的 item 是对象, 里面有各种数据,
      // 应该根据枚举字典的顺序组成一个数组方便转成 excel
      for (const key in dictionary) {
        const enKey = dictionary[key]
        // 找出item里每一个英文key对应的值
        let value = item[enKey]
        // 如果数据处理的是事件或者聘用形式, 需要额外处理
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = formatDate(value)
        }
        // 如果是聘用形式的数据. 去全局枚举中找到对应的值替换回来
        if (enKey === 'formOfEmployment') {
          const obj = EmploymentEnum.hireType.find(item => item.id === value)
          value = obj ? obj.value : '不确定的临时工'
        }
        array.push(value)
      }
      return array
    },
    async getUserList() {
      const { rows, total } = await getUserList(this.pageSetting)
      this.pageSetting.total = total
      this.list = rows
    },
    currentChange(newPage) {
      this.pageSetting.page = newPage
      this.getUserList()
    },
    sizeChange(newSize) {
      this.pageSetting.size = newSize
      this.getUserList()
    },
    // 遍历找到每个id下对应的值 并输出
    formatEmployment(row, column, cellValue, index) {
      const obj = EmploymentEnum.hireType.find(item => item.id === cellValue)
      // 如果没有Id那就找不到Obj，所以要有一个防御型编程
      return obj ? obj.value : '其他'
    },
    // formatTimeEntry(row, column, cellValue, index) {
    //   // 日期 T 事件
    //   return cellValue.split('T')[0] || '待定'
    // }
    async delEmployee(id) {
      try {
        await this.$confirm('请确认删除该员工')
        await delEmployee(id)
        // 不仅要加载数据而且要让数据保存到列表当中，所以要调用当前方法中的getUserList
        await this.getUserList()
        this.$message.success('成功删除员工')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>

</style>
